<?php

namespace App\Services\Admin;

use App\Services\Service;
use App\Models\Dept;

class DeptService extends Service
{
    public static function options(): array
    {
        $list = Dept::orderBy('sort', 'asc')->get()->toArray();

        $list = array_map(fn($item) => [
            'value' => $item['id'],
            'label' => $item['name'],
            'parentId' => $item['parentId'],
        ], $list);

        return self::buildOptionsTree($list);
    }

    public static function index(array $params): array
    {

        $query = Dept::orderBy('sort', 'asc');

        if (!empty($params['keywords'])) {
            $query->where('name', 'like', "%{$params['keywords']}%")->orWhere('code', 'like', "%{$params['keywords']}%");
        }

        if (isset($params['status'])) {
            $query->where('status', (int)$params['status']);
        }

        $list = $query->get()->makeVisible(['createTime', 'updateTime'])->toArray();

        return self::buildTree($list);
    }

    public static function store(array $data): array
    {

        $dept = Dept::create($data);

        return [
            'id' => $dept->id,
        ];
    }

    public static function show(string $id): array
    {
        $dept = Dept::find($id);

        if (!$dept) {
            self::throwValidationException('id', ['部门不存在']);
        }

        return $dept->toArray();
    }

    public static function update(array $data, string $id): array
    {
        $dept = Dept::find($id);

        if (!$dept) {
            self::throwValidationException('id', ['部门不存在']);
        }

        $dept->update($data);

        return [
            'id' => $dept->id,
        ];
    }

    public static function destroy(string $id): array
    {
        $dept = Dept::find($id);

        if (!$dept) {
            self::throwValidationException('id', ['部门不存在']);
        }

        // 检查是否有子部门
        $childCount = Dept::where('parentId', $id)->count();
        if ($childCount > 0) {
            self::throwValidationException('id', ['该部门存在子部门，无法删除']);
        }

        $dept->delete();

        return [
            'id' => $dept->id
        ];
    }
}
